<template>
    <div>
        <div style='margin-bottom: 20px;padding: 0 20px;box-sizing: border-box;'>
            <a-form ref="formRef" name="advanced_search" class="ant-advanced-search-form" :model="formState"
                @finish="onFinish" style="margin-top: 30px;">
                <a-row :gutter="24">
                    <a-col :span="6">
                        <a-form-item name="name" label="优惠卷名称">
                            <a-input v-model:value="formState[`name`]"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item name="user_uid" label="拥有者uid">
                            <a-input v-model:value="formState[`user_uid`]"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item name="used_date" label="使用日期">
                            <a-range-picker v-model:value="formState['used_date']" show-time format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item name="goods_uid" label="使用订单">
                            <a-input v-model:value="formState[`goods_uid`]" placeholder="请输入uid"
                                :disabled="formState.uid_type != ''"></a-input>
                            <a-form-item-rest>
                                <a-radio-group v-model:value="formState['uid_type']">
                                    <a-radio-button value="">全部</a-radio-button>
                                    <a-radio-button value="A">已使用</a-radio-button>
                                    <a-radio-button value="B">未使用</a-radio-button>
                                </a-radio-group>
                            </a-form-item-rest>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item name="expiring_date" label="优惠卷有效期（天以内）">
                            <a-input v-model:value="formState[`expiring_date`]" placeholder="请输入天数 可以使用> < 符号 进行范围查找"
                                :disabled="formState.date_type != 'C'"></a-input>
                            <a-form-item-rest>
                                <a-radio-group v-model:value="formState['date_type']">
                                    <a-radio-button value="">全部</a-radio-button>
                                    <a-radio-button value="A">未开始</a-radio-button>
                                    <a-radio-button value="B">已失效</a-radio-button>
                                    <a-radio-button value="C">有效期</a-radio-button>
                                </a-radio-group>
                            </a-form-item-rest>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item name="amount" label="优惠金额">
                            <a-input v-model:value="formState[`amount`]" placeholder="请输入金额 可以使用> < 符号 进行范围查找"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item name="promoter" label="优惠卷发起人">
                            <a-input v-model:value="formState[`promoter`]" placeholder="请输入"></a-input>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="20" style="text-align: left;margin-bottom: -50px;z-index: 100;">
                        <a-button type="primary" @click="adds">新增</a-button>
                    </a-col>
                    <a-col :span="24" style="text-align: right">
                        <a-button type="primary" html-type="submit">查询</a-button>
                        <a-button style="margin: 0 8px" @click="() => onreset()">重置</a-button>

                    </a-col>
                </a-row>
            </a-form>
            <a-table bordered :data-source="dataSource" :columns="columns"
                :pagination="{ current, pageSize, total: totalCount }" @change="pageClick">

                <template #bodyCell="{ column, text, record }">

                    <template v-if="column.dataIndex == 'expiring_date'">
                        <span style="color: gray;" v-if="share.calculateRemainingDays(record.take_date) != false">未开始</span>
                        <span style="color:green" v-else-if="share.calculateRemainingDays(record.expiring_date)">{{
                            share.calculateRemainingDays(record.expiring_date) + '天以内' }} </span>
                        <span style="color:red" v-else>已失效</span>
                    </template>

                    <template v-if="column.dataIndex === 'operation'">
                        <a-popconfirm :title="'真的要删除吗'" @confirm="deleCuo(record.uid)" v-if="!record.goods_uid">
                            <a :style="{ color: share.color, marginLeft: '15px' }">删除</a>
                        </a-popconfirm>
                        <span :style="{ marginLeft: '15px', color: share.color }" @click="showModal(record)">修改</span>
                        <span :style="{ marginLeft: '15px', color: share.color }" @click="showXq(record)">详情</span>
                    </template>
                    <template v-if="column.dataIndex == 'image'">
                        <a-image :width="50" :heigth="50" :src='share.http + `/${record.dir}/${record.image}`' />
                    </template>
                </template>
            </a-table>
        </div>

        <!-- 修改操作 -->
        <a-modal v-model:visible="setModel" title="优惠卷修改" :width="740" @ok="setOk" :destroyOnClose="true">
            <div>

                <div style="font-size: 18px;color: #333;margin-bottom: 10px;">优惠卷到期时间修改:</div>
                <a-date-picker v-model:value="setData.ex_date" show-time type="date" placeholder="Pick a date"
                    style="width: 55%" />
            </div>
        </a-modal>
        <!-- 新增操作 -->
        <a-modal v-model:visible="addModel" title="优惠卷添加" :width="650" @ok="addOk" :destroyOnClose="true">
            <div>
                <!-- 优惠卷名称 -->
                <a-form ref="addRef" :model="addState">
                    <a-form-item label="优惠卷名称" name="name" :rules="[{ required: true, message: '请输入优惠卷名称!' }]">
                        <a-input v-model:value="addState.name" />
                    </a-form-item>
                    <!-- 优惠卷有效期 -->
                    <a-form-item label="优惠卷有效期" name="date" :rules="[{ required: true, message: '请选择优惠卷有效期!' }]">
                        <a-range-picker v-model:value="addState['date']" show-time format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss" />
                    </a-form-item>
                    <!-- 优惠卷金额 -->
                    <a-form-item label="优惠卷抵押金额" name="amount" :rules="[{ required: true, message: '请输入抵押金额!' }]">
                        <a-input-number v-model:value="addState['amount']" prefix="￥" />
                    </a-form-item>
                    <!-- 优惠卷要求 -->
                    <a-form-item label="优惠卷要求金额" name="accumulate" :rules="[{ required: true, message: '请输入要求金额!' }]">
                        <a-input-number v-model:value="addState['accumulate']" prefix="￥" />
                    </a-form-item>
                    <!-- 范围群体 -->
                    <a-form-item label="选择优惠卷群体" name="users" :rules="[{ required: true, message: '请选择用户群体!' }]">
                        <a-radio-group v-model:value="addState['users']" @change="usersChange">
                            <a-radio value="a">指定用户</a-radio>
                            <a-radio value="b">新用户</a-radio>
                            <a-radio value="c">所有用户</a-radio>
                            <a-radio value="d">时间范围内的用户</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <!-- 指定用户 -->
                    <div v-show="addState['users'] == 'a'">
                        <a-form-item label="指定用户手机号" :rules="[
                            { required: true, message: '请输入说明!' },
                            { pattern: /^[A-Za-z0-9]{13}$/, message: '请输入十一位数字的组合' }
                        ]">
                            <a-select v-model:value="addState.userPhone" mode="tags" placeholder="请输入11位字段手机号"
                                @select="validateUserPhone" @deselect="deleUserPhone"></a-select>
                        </a-form-item>
                        <!-- 指定用户名单 -->
                        <a-table :columns="usercolumns" :data-source="userData" bordered :scroll="{ y: 800 }">
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.dataIndex == 'cao'">
                                    <a-popconfirm :title="'真的要删除吗？'" @confirm="deleUserPhone(record.phone, true)">
                                        <a :style="{ color: share.color }">删除</a>
                                    </a-popconfirm>
                                </template>
                            </template>
                        </a-table>
                    </div>
                    <!-- 新用户 -->
                    <div v-show="addState['users'] == 'b'">
                        <a-table :columns="usercolumns" :data-source="selUserData" bordered :scroll="{ y: 800 }"
                            :pagination="{ current: currentUsers, pageSize, total: blackList.totalCount }"
                            @change="UserPageClick">
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.dataIndex == 'cao'">
                                    <a-popconfirm :title="'真的要加入不参与吗？'" @confirm="removeUser(record.phone)">
                                        <a :style="{ color: share.color }">不参与优惠卷</a>
                                    </a-popconfirm>
                                </template>
                            </template>
                        </a-table>
                        <div style="margin-top: 20px;">排除用户:</div>
                        <!-- 排除用户名单 -->
                        <a-table :columns="usercolumns" :data-source="blackList.xin" bordered :scroll="{ y: 800 }">
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.dataIndex == 'cao'">
                                    <a-popconfirm :title="'真的要移出吗？'" @confirm="removeUser(record.phone, true)">
                                        <a :style="{ color: share.color }">移除</a>
                                    </a-popconfirm>
                                </template>
                            </template>
                        </a-table>
                    </div>
                    <!-- 所有用户 -->
                    <div v-show="addState['users'] == 'c'">
                        <a-table :columns="usercolumns" :data-source="selUserData" bordered :scroll="{ y: 800 }"
                            :pagination="{ current: currentUsers, pageSize, total: blackList.totalCount }"
                            @change="UserPageClick">
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.dataIndex == 'cao'">
                                    <a-popconfirm :title="'真的要加入不参与吗？'" @confirm="removeUser(record.phone)">
                                        <a :style="{ color: share.color }">不参与优惠卷</a>
                                    </a-popconfirm>
                                </template>
                            </template>
                        </a-table>
                        <div style="margin-top: 20px;">排除用户:</div>
                        <!-- 排除用户名单 -->
                        <a-table :columns="usercolumns" :data-source="blackList.all" bordered :scroll="{ y: 800 }">
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.dataIndex == 'cao'">
                                    <a-popconfirm :title="'真的要移出吗？'" @confirm="removeUser(record.phone, true)">
                                        <a :style="{ color: share.color }">移除</a>
                                    </a-popconfirm>
                                </template>
                            </template>
                        </a-table>
                    </div>
                    <!-- 时间范围内的用户 -->
                    <div v-show="addState['users'] == 'd'">
                        <a-range-picker :show-time="{ format: 'HH:mm' }" format="YYYY-MM-DD HH:mm"
                            :placeholder="['起始', '结束']" @ok="onRangeOk" />
                        <a-table :columns="usercolumns" :data-source="selUserData" bordered :scroll="{ y: 800 }"
                            :pagination="{ current: currentUsers, pageSize, total: blackList.totalCount }"
                            @change="UserPageClick">
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.dataIndex == 'cao'">
                                    <a-popconfirm :title="'真的要加入不参与吗？'" @confirm="removeUser(record.phone)">
                                        <a :style="{ color: share.color }">不参与优惠卷</a>
                                    </a-popconfirm>
                                </template>
                            </template>
                        </a-table>
                        <div style="margin-top: 20px;">排除用户:</div>
                        <!-- 排除用户名单 -->
                        <a-table :columns="usercolumns" :data-source="blackList.date" bordered :scroll="{ y: 800 }">
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.dataIndex == 'cao'">
                                    <a-popconfirm :title="'真的要移出吗？'" @confirm="removeUser(record.phone, true)">
                                        <a :style="{ color: share.color }">移除</a>
                                    </a-popconfirm>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </a-form>
            </div>
        </a-modal>
        <!-- 详情操作 -->
        <a-modal v-model:visible="xqModal" title="优惠卷详情" :width="740" @ok="xqOk" :destroyOnClose="true">
            <div class="xqBox">
                <p>
                    <span class="title">优惠卷名称:</span>
                    <span class="value">{{ xqData.name }}</span>
                </p>
                <p>
                    <span class="title">拥有人UID:</span>
                    <span class="value" style="color: #333;">{{ xqData.user_uid }}</span>
                </p>
                <p>
                    <span class="title">优惠卷UID:</span>
                    <span class="value">{{ xqData.uid }}</span>
                </p>
                <p>
                    <span class="title">使用订单UID:</span>
                    <span class="value" style="color: #333;">{{ xqData.goods_uid }}</span>
                </p>
                <p style="margin-top: 20px;">
                    <span class="title" style="margin-top: 20px;">创建日期:</span>
                    <span class="value">{{ xqData.take_date }}</span>
                </p>
                <p style="margin-top: 20px;">
                    <span class="title">使用日期:</span>
                    <span class="value">{{ xqData.used_date }}</span>
                </p>
                <p style="width: 100%;">
                    <span class="title">失效日期:</span>
                    <span class="value">{{ xqData.expiring_date }}</span>
                </p>
                <p style="margin-top: 20px;">
                    <span class="title">优惠卷发起人:</span>
                    <span class="value" style="color: #333;">{{ xqData.username }}</span>
                </p>
                <p style="margin-top: 20px;">
                    <span class="title">订单满金额可用(元):</span>
                    <span class="value" style="color: #333;">{{ xqData.accumulate }}</span>
                </p>
                <p>
                    <span class="title">优惠金额（元）:</span>
                    <span class="value" style="color: #333;">{{ xqData.amount }}</span>
                </p>

            </div>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { } from '@ant-design/icons-vue';
import { useUserData } from '../../../stores/userData';
import { useRouter } from 'vue-router';
import share from '../../../util/commnet'
import { message } from 'ant-design-vue';
import { couponAPI } from '../../../api/coupon';
import dayjs from 'dayjs';
import {debounce} from 'lodash'
const store = useUserData();
const router = useRouter();

const formRef = ref('');    //搜索数据
const setModel = ref(false);
const formState = reactive({  //搜素内容
    name: '',
    user_uid: "",
    used_date: [],
    goods_uid: '',
    accumulate: "",
    amount: "",
    promoter: "",
    expiring_date: '',
    uid_type: '',
    date_type: "",
});
const dataSource = ref([{}]);   //表格数据
const totalCount = ref(0);      //总条
const pageSize = ref(10);       //一页多少条
const current = ref(1);         //当前页
const columns = [{
    title: '优惠卷名称',
    dataIndex: 'name',
    align: 'center'

}, {
    title: '拥有者uid',
    dataIndex: 'user_uid',
    align: 'center'

}, {
    title: "使用日期",
    dataIndex: "used_date",
    align: 'center',

}, {
    title: '使用订单',
    dataIndex: 'goods_uid',
    align: 'center'

}, {
    title: "满额可用 （元）",
    dataIndex: 'accumulate',
    align: 'center'

}, {
    title: '优惠金额（元）',
    dataIndex: 'amount',
    align: 'center'

}, {
    title: "优惠卷发起人",
    dataIndex: "promoter",
    align: 'center'

}, {
    title: "有效期 （天）",
    dataIndex: "expiring_date",
    align: 'center'

}, {
    title: '操作',
    dataIndex: 'operation',
    align: 'center'

}];

const onreset = () => {  //点击查询条件的重置
    formRef.value.resetFields();
    formState.date_type = "";
    formState.uid_type = "";
    console.log(formState);
    onFinish()
}

const onFinish = () => {  //条件查询
    console.log(formState);
    pageClick();
}


const debouncedPageClick = debounce(async (item) => {           //进行防抖
    item ? current.value = item.current : current.value = 1;
    let res = await couponAPI(`select|${formState.name}|${formState.user_uid}|${formState.used_date}|${formState.goods_uid}|${formState.accumulate}|${formState.amount}|${formState.promoter}|${formState.expiring_date}|${formState.date_type}|${formState.uid_type}|${pageSize.value}|${current.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    console.log(res);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {

        message.error(res.message);
        return
    }
    dataSource.value = res.data
    totalCount.value = res.total - 0;
}, 300);

const pageClick = (item) => {       //页面变化刷新表格
    debouncedPageClick(item);
};


// 修改操作-----------------------------------------------------------------
const setData = reactive({
    ex_date: '',
    uid: '',
    yuan_date: ''
})  //有效期

const showModal = (item) => { //修改优惠卷
    setModel.value = true;
    setData.ex_date = dayjs(item.expiring_date);
    setData.yuan_date = dayjs(item.expiring_date);
    setData.uid = item.uid;
}

const setOk = async () => {
    const ex_date = setData.ex_date.format('YYYY-MM-DD HH:mm:ss');
    const yuan_date = setData.yuan_date.format('YYYY-MM-DD HH:mm:ss');

    if (ex_date != yuan_date) {
        let res = await couponAPI(`set|${setData.uid}|${ex_date}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
        console.log(res);
        if (!res || res.code == 406) {                //验证账号状态
            router.replace({ name: 'login' });
            message.error("账号失效", 3)
            return;
        } else if (res.code != 200) {
            message.error(res.message);
            return
        }
        message.success("修改成功");
        setModel.value = false;
        pageClick();
    }


}

// 删除操作------------------------------------------------------------------
const deleCuo = async (uid) => {   //删除优惠卷
    let res = await couponAPI(`dele|${uid}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);

    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {
        message.error(res.message);
        return
    }
    message.success("删除成功");
    pageClick();
}

// 添加操作-----------------------------------------------------------------------
const addModel = ref(false);
const addRef = ref(null);
const addState = reactive({
    name: '',
    date: [],
    users: "a",
    accumulate: '',
    amount: '',
    userPhone: []
})
const usercolumns = [
    {
        title: "名称",
        dataIndex: "nickname",
        key: "nickname"
    },
    {
        title: "手机号",
        dataIndex: 'phone',
        key: "phone"
    },
    {
        title: "操作",
        dataIndex: "cao",
    }
]
const userData = ref([]);       //指定用户名单
const selUserData = ref([]);  //查看用户表格
const selectLength = ref(-1);


const UserPageClick = async (item) => {   //享受优惠卷用户的群体分页
    currentUsers.value = item.current;
    if (addState.users == 'b') {  //新用户
        let res = await couponAPI(`selectUserXin|${currentUsers.value}|${pageSize.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
        console.log(res);
        if (!res || res.code == 406) {                //验证账号状态
            router.replace({ name: 'login' });
            message.error("账号失效", 3)
            return;
        } else if (res.code != 200) {
            message.error(res.message)
            return
        }
        selUserData.value = res.data.filter(item => {
            return blackList.xin.every(i => i.phone != item.phone)
        });
        blackList.totalCount = res.total;
    } else if (addState.users == 'c') { //所有用户
        let res = await couponAPI(`selectUserAll|${currentUsers.value}|${pageSize.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
        console.log(res);
        if (!res || res.code == 406) {                //验证账号状态
            router.replace({ name: 'login' });
            message.error("账号失效", 3)
            return;
        } else if (res.code != 200) {
            message.error(res.message)
            return
        }
        selUserData.value = res.data.filter(item => {
            return blackList.all.every(i => i.phone != item.phone)
        });
        blackList.totalCount = res.total;
    } else if (addState.users == 'd') {
        let res = await couponAPI(`selectUserDate|${blackList.date_time}|${currentUsers.value}|${pageSize.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
        console.log(res);
        if (!res || res.code == 406) {                //验证账号状态
            router.replace({ name: 'login' });
            message.error("账号失效", 3)
            return;
        } else if (res.code != 200) {
            message.error(res.message)
            return
        }
        selUserData.value = res.data.filter(item => {
            return blackList.date.every(i => i.phone != item.phone)
        });
        blackList.totalCount = res.total;
    }
}


const blackList = reactive({
    xin: [],
    all: [],
    date: [],
    totalCount: 0,   //总条数
    date_time: [],
    xin_total: '',
    all_total: '',
    date_total: ''
});  //黑名单的数据
const currentUsers = ref(1); //当前用户列表多少页

const usersChange = async (v) => {  //当用户群体发生改变
    selUserData.value = []
    const key = v.target.value;
    current.value = 1;  //重新回归第一页
    if (key == 'b') {  //新用户
        let res = await couponAPI(`selectUserXin|${currentUsers.value}|${pageSize.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
        console.log(res);
        if (!res || res.code == 406) {                //验证账号状态
            router.replace({ name: 'login' });
            message.error("账号失效", 3)
            return;
        } else if (res.code != 200) {
            message.error(res.message)
            return
        }
        selUserData.value = res.data.filter(item => {
            return blackList.xin.every(i => i.phone != item.phone)
        });
        blackList.totalCount = res.total;
        blackList.xin_total = res.total;
    } else if (key == 'c') { //所有用户
        let res = await couponAPI(`selectUserAll|${currentUsers.value}|${pageSize.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
        console.log(res);
        if (!res || res.code == 406) {                //验证账号状态
            router.replace({ name: 'login' });
            message.error("账号失效", 3)
            return;
        } else if (res.code != 200) {
            message.error(res.message)
            return
        }
        selUserData.value = res.data.filter(item => {
            return blackList.all.every(i => i.phone != item.phone)
        });
        blackList.totalCount = res.total;
        blackList.all_total = res.total;
    } else if (key == 'd') {
        if (!blackList.date_time[0] || !blackList.date_time[1]) return
        let res = await couponAPI(`selectUserDate|${blackList.date_time}|${currentUsers.value}|${pageSize.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
        console.log(res);
        if (!res || res.code == 406) {                //验证账号状态
            router.replace({ name: 'login' });
            message.error("账号失效", 3)
            return;
        } else if (res.code != 200) {
            message.error(res.message)
            return
        }
        selUserData.value = res.data.filter(item => {
            return blackList.date.every(i => i.phone != item.phone)
        });
        blackList.totalCount = res.total;
        blackList.date_total = res.total;
    }
}

const removeUser = (phone, k = false) => {   //用户群里之间的相互移除操作
    if (addState.users == 'c') {
        if (!k) {
            const user = selUserData.value.find(item => item.phone == phone);     //找出用户
            selUserData.value = selUserData.value.filter(item => item.phone != phone)  //将选择的用户不加入优惠
            blackList.all.push(user)
        } else {
            blackList.all = blackList.all.filter(item => item.phone != phone);
        }
    } else if (addState.users == 'b') {
        if (!k) {
            const user = selUserData.value.find(item => item.phone == phone);     //找出用户
            selUserData.value = selUserData.value.filter(item => item.phone != phone)  //将选择的用户不加入优惠
            blackList.xin.push(user)
        } else {
            blackList.xin = blackList.xin.filter(item => item.phone != phone);
        }
    } else if (addState.users == 'd') {
        if (!k) {
            const user = selUserData.value.find(item => item.phone == phone);     //找出用户
            selUserData.value = selUserData.value.filter(item => item.phone != phone)  //将选择的用户不加入优惠
            blackList.date.push(user)
        } else {
            blackList.date = blackList.date.filter(item => item.phone != phone);
        }
    }

}

const onRangeOk = async (v) => {   //时间范围的用户选择完成时间显示数据
    current.value = 1;
    if (!v[0] || !v[1]) return;

    blackList.date_time[0] = (v[0].format("YYYY-MM-DD HH:mm:ss"))
    blackList.date_time[1] = (v[1].format("YYYY-MM-DD HH:mm:ss"))
    let res = await couponAPI(`selectUserDate|${blackList.date_time}|${currentUsers.value}|${pageSize.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    console.log(res);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {
        message.error(res.message)
        return
    }
    selUserData.value = res.data.filter(item => {
        return blackList.date.every(i => i.phone != item.phone)
    });
    blackList.totalCount = res.total;
    blackList.date_total = res.total;
}

const validateUserPhone = async () => {  //验证添加的制定手机号是否存在    
    const regex = /^1\d{10}$/;
    addState.userPhone = addState.userPhone.filter(phone => regex.test(phone));   //判断是否满足手机号格式
    if (selectLength.value == addState.userPhone.length || addState.userPhone.length == 0) return;
    let res = await couponAPI(`selectUser|${addState.userPhone.at(-1)}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    console.log(res);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code == 200 && res.data.length < 1) {   //查询数据但是未找到的情况
        message.error(res.message + "用户:" + addState.userPhone.at(-1) + " 可能被冻结", 2.5);
        addState.userPhone.pop();
        return
    } else if (res.code != 200) {
        message.error(res.message)
        return
    }
    userData.value.push(res.data[0])
    selectLength.value = addState.userPhone.length;
}

const deleUserPhone = (phone, k = false) => {  //点击指定用户的取消时
    if (k) addState.userPhone = addState.userPhone.filter(item => item != phone);
    userData.value = userData.value.filter(item => item.phone != phone);
    selectLength.value = addState.userPhone.length;  //修改select的长度 以便进行后续判断

}

const adds = () => {   //开启添加模块
    addModel.value = true;
}
const coms = () => {      //添加完成以后
    addRef.value.resetFields();
    addState.userPhone = [];
    userData.value = [];
    blackList.all = [];
    blackList.all_total = '';
    blackList.date = [];
    blackList.date_time = [];
    blackList.date_total = '';
    blackList.totalCount = '';
    blackList.xin = [];
    blackList.xin_total = '';
    addModel.value = false;
    pageClick();
}
const addOk = () => {
    addRef.value.validateFields()
        .then(async res => {

            if (addState.users == 'a') {  //添加为指定用户
                if (userData.value.length < 1) {
                    message.error("指定用户为空，无法添加优惠卷")
                    return
                }
                let add = await couponAPI(`add|A|${addState.name}|${addState.date}|${addState.accumulate}|${addState.amount}|${userData.value.map(item => item.phone)}|${store.data.uid}||${store.data.token}|${store.data.uuid}|${store.data.phone}`)
                if (!add || add.code == 406) {                //验证账号状态
                    router.replace({ name: 'login' });
                    message.error("账号失效", 3)
                    return;
                } else if (add.code != 200) {

                    message.error(add.message);
                    return
                }
                message.success(add.message);
                coms()
            } else if (addState.users == 'b') {     //新用户添加
                if (blackList.xin.length >= blackList.xin_total) {  //当排除的用户 == 总数 则没有用户可以拿到优惠卷
                    message.error("指定用户为空，无法添加优惠卷");
                    return
                }
                let add = await couponAPI(`add|B|${addState.name}|${addState.date}|${addState.accumulate}|${addState.amount}|${blackList.xin.map(item => item.phone)}|${store.data.uid}||${store.data.token}|${store.data.uuid}|${store.data.phone}`)
                console.log(add);
                if (!add || add.code == 406) {                //验证账号状态
                    router.replace({ name: 'login' });
                    message.error("账号失效", 3)
                    return;
                } else if (add.code != 200) {
                    message.error(add.message);
                    return
                }
                message.success(add.message);
                coms()
            } else if (addState.users == 'c') {         //所有用户添加
                if (blackList.all.length >= blackList.all_total) {  //当排除的用户 == 总数 则没有用户可以拿到优惠卷
                    message.error("指定用户为空，无法添加优惠卷");
                    return
                }
                let add = await couponAPI(`add|C|${addState.name}|${addState.date}|${addState.accumulate}|${addState.amount}|${blackList.all.map(item => item.phone)}|${store.data.uid}||${store.data.token}|${store.data.uuid}|${store.data.phone}`)
                console.log(add);
                if (!add || add.code == 406) {                //验证账号状态
                    router.replace({ name: 'login' });
                    message.error("账号失效", 3)
                    return;
                } else if (add.code != 200) {
                    message.error(add.message);
                    return
                }
                message.success(add.message);
                coms()
            } else if (addState.users == 'd') {      //时间范围用户
                if (blackList.date.length >= blackList.date_total) {  //当排除的用户 == 总数 则没有用户可以拿到优惠卷
                    message.error("指定用户为空，无法添加优惠卷");
                    return
                }
                let add = await couponAPI(`add|D|${addState.name}|${addState.date}|${addState.accumulate}|${addState.amount}|${blackList.date.map(item => item.phone)}|${store.data.uid}|${blackList.date_time}|${store.data.token}|${store.data.uuid}|${store.data.phone}`)
                console.log(add);
                if (!add || add.code == 406) {                //验证账号状态
                    router.replace({ name: 'login' });
                    message.error("账号失效", 3)
                    return;
                } else if (add.code != 200) {
                    message.error(add.message);
                    return
                }
                message.success(add.message);
                coms()
            }
        })



}


// 详情操作------------------------------------------------------
const xqModal = ref(false)
const xqData = ref('');
const xqOk = () => {

    xqModal.value = false;
}
const showXq = (item) => {
    xqData.value = item;
    console.log(item);
    xqModal.value = true;
}
onMounted(async () => {
    let res = await couponAPI(`select|${formState.name}|${formState.user_uid}|${formState.used_date}|${formState.goods_uid}|${formState.accumulate}|${formState.amount}|${formState.promoter}|${formState.expiring_date}|${formState.date_type}|${formState.uid_type}|${pageSize.value}|${current.value}|${store.data.token}|${store.data.uuid}|${store.data.phone}`);
    console.log(res);
    if (!res || res.code == 406) {                //验证账号状态
        router.replace({ name: 'login' });
        message.error("账号失效", 3)
        return;
    } else if (res.code != 200) {
        message.error(res.message);
        return
    }

    dataSource.value = res.data;
    totalCount.value = res.total - 0;

})
</script>


<style scoped src="../../css/coupon/coupon.scss" />
